<template>
  <div class="admin-management">
    <div class="tab-content">
      <!-- 操作按钮 -->
      <div class="action-bar">
        <el-input v-model="searchTerm" placeholder="请输入搜索关键词" style="width: 240px; margin-right: 10px;" clearable />
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button type="primary" @click="handleCreateAdmin" style="margin-left: 10px;">
          <el-icon><Plus /></el-icon>
          新增管理员
        </el-button>
      </div>

      <!-- 管理员列表 -->
      <el-card class="table-card">
        <el-table :data="adminData" style="width: 100%" v-loading="loading">
          <el-table-column prop="id" label="管理员ID" min-width="10%" />
          <el-table-column prop="username" label="用户名" min-width="12%" />
          <el-table-column prop="fullName" label="姓名" min-width="12%" />
          <el-table-column prop="role" label="角色" min-width="12%">
            <template #default="scope">
              <el-tag :type="getRoleType(scope.row.role)">
                {{ getRoleText(scope.row.role) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="permissions" label="权限" min-width="15%">
            <template #default="scope">
              <el-tag
                v-for="permission in scope.row.permissions"
                :key="permission"
                size="small"
                style="margin-right: 4px; margin-bottom: 4px;"
              >
                {{ permissionMap[permission] || permission }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" min-width="10%">
            <template #default="scope">
              <el-tag :type="getStatusType(scope.row.status)">
                {{ getStatusText(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" min-width="15%" />
          <el-table-column prop="lastLoginTime" label="最后登录" min-width="15%" />
          <el-table-column label="操作" min-width="16%">
            <template #default="scope">
              <el-button type="primary" size="small" @click="handleEditAdmin(scope.row)">
                编辑
              </el-button>
              <el-button type="warning" size="small" @click="handleAssignRole(scope.row)">
                分配角色
              </el-button>
              <el-button 
                v-if="scope.row.id !== 'ADMIN001'"
                type="danger" 
                size="small" 
                @click="handleDeleteAdmin(scope.row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>

    <!-- 新增/编辑管理员对话框 -->
    <el-dialog
      v-model="adminDialogVisible"
      :title="isEditAdmin ? '编辑管理员' : '新增管理员'"
      width="50%"
    >
      <el-form :model="adminForm" label-width="100px" v-if="adminForm">
        <el-form-item label="用户名" required>
          <el-input v-model="adminForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" v-if="!isEditAdmin" required>
          <el-input v-model="adminForm.password" type="password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="确认密码" v-if="!isEditAdmin" required>
          <el-input v-model="adminForm.confirmPassword" type="password" placeholder="请确认密码" />
        </el-form-item>
        <el-form-item label="新密码" v-if="isEditAdmin && canModifyAccount()">
          <el-input v-model="adminForm.newPassword" type="password" placeholder="如需修改请输入新密码" />
        </el-form-item>
        <el-form-item v-if="isEditAdmin && !canModifyAccount()">
          <el-alert
            title="权限不足"
            description="只有超级管理员可以修改账号密码"
            type="warning"
            :closable="false"
          />
        </el-form-item>
        <el-form-item label="姓名" required>
          <el-input v-model="adminForm.fullName" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="角色名称" required>
          <el-select v-model="adminForm.roleName" placeholder="请选择角色" @change="handleRoleChange">
            <el-option
              v-for="role in roleList"
              :key="role.roleId"
              :label="role.roleName"
              :value="role.roleName"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="权限">
          <div style="color: #909399; font-size: 12px;">
            权限将根据选择的角色自动设置
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="adminDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleConfirmAdmin">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 分配角色对话框 -->
    <el-dialog
      v-model="roleDialogVisible"
      title="分配角色"
      width="40%"
    >
      <el-form :model="roleForm" label-width="100px" v-if="roleForm">
        <el-form-item label="管理员">
          <span>{{ roleForm.username }}</span>
        </el-form-item>
        <el-form-item label="当前角色">
          <el-tag :type="getRoleType(roleForm.currentRole)">
            {{ getRoleText(roleForm.currentRole) }}
          </el-tag>
        </el-form-item>
        <el-form-item label="新角色">
          <el-select v-model="roleForm.newRole" placeholder="请选择新角色">
            <el-option
              v-for="role in roleList"
              :key="role.roleId"
              :label="role.roleName"
              :value="role.roleName"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="roleDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleConfirmRole">确认分配</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getAdminUserList, searchAdminUsers, getAdminUserDetail, createAdminUser, updateAdminUser, deleteAdminUser, getAdminPermissionsInfo } from '@/api/adminUser'
import { getAdminRoleList } from '@/api/adminRole'
import { canModifyAccount } from '@/utils/permission'

const loading = ref(false)
const adminDialogVisible = ref(false)
const roleDialogVisible = ref(false)
const isEditAdmin = ref(false)
const adminForm = ref(null)
const roleForm = ref(null)

const searchTerm = ref('')

const editingAdminId = ref(null)

const permissionMap = ref({})
const permissionsDescription = ref('')

const roleList = ref([])

const adminData = ref([])

const getRoleType = (role) => {
  const roleMap = {
    '超级管理员': 'danger',
    '审核员': 'warning',
    '撮合员': 'success',
    '内容编辑员': 'info'
  }
  return roleMap[role] || 'info'
}

const getRoleText = (role) => {
  // 直接返回角色名称，因为后端返回的就是中文角色名
  return role || '未知'
}

const getStatusType = (status) => {
  const statusMap = {
    active: 'success',
    inactive: 'danger'
  }
  return statusMap[status] || 'info'
}

const getStatusText = (status) => {
  const statusMap = {
    active: '正常',
    inactive: '禁用'
  }
  return statusMap[status] || '未知'
}

const handleCreateAdmin = () => {
  isEditAdmin.value = false
  adminForm.value = {
    username: '',
    password: '',
    confirmPassword: '',
    fullName: '',
    roleName: '',
    permissions: []
  }
  adminDialogVisible.value = true
}

const handleEditAdmin = async (row) => {
  isEditAdmin.value = true
  editingAdminId.value = row.id
  loading.value = true
  try {
    const res = await getAdminUserDetail(row.id)
    if (res && res.code === 200 && res.data) {
      const item = res.data
      adminForm.value = {
        username: item.username,
        fullName: item.full_name || '',
        roleName: item.role_name || '审核员',
        permissions: item.permissions || [],
        newPassword: ''
      }
      adminDialogVisible.value = true
    } else {
      ElMessage.error(res?.message || '获取管理员详情失败')
    }
  } catch (e) {
  } finally {
    loading.value = false
  }
}

const handleAssignRole = (row) => {
  roleForm.value = {
    id: row.id,
    username: row.username,
    currentRole: row.role,
    newRole: row.role
  }
  roleDialogVisible.value = true
}

const handleDeleteAdmin = (row) => {
  ElMessageBox.confirm(
    '确定要删除该管理员吗？',
    '确认操作',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    loading.value = true
    try {
      const res = await deleteAdminUser(row.id)
      if (res && res.code === 200) {
        ElMessage.success('管理员删除成功')
        await loadAdminList()
      } else {
        ElMessage.error(res?.message || '删除管理员失败')
      }
    } catch (e) {
    } finally {
      loading.value = false
    }
  })
}

const handleConfirmAdmin = async () => {
  try {
    loading.value = true
    if (isEditAdmin.value) {
      const payload = {
        username: adminForm.value.username,
        fullName: adminForm.value.fullName,
        roleName: adminForm.value.roleName,
        permissions: adminForm.value.permissions
      }
      
      // 只有超级管理员可以修改密码
      if (canModifyAccount() && adminForm.value.newPassword) {
        payload.newPassword = adminForm.value.newPassword
      }
      
      const res = await updateAdminUser(editingAdminId.value, payload)
      if (res && res.code === 200) {
        ElMessage.success('管理员信息已更新')
        adminDialogVisible.value = false
        await loadAdminList()
      } else {
        ElMessage.error(res?.message || '更新管理员失败')
      }
    } else {
      const payload = {
        username: adminForm.value.username,
        password: adminForm.value.password,
        fullName: adminForm.value.fullName,
        roleName: adminForm.value.roleName,
        permissions: adminForm.value.permissions
      }
      const res = await createAdminUser(payload)
      if (res) {
        ElMessage.success('管理员已创建')
        adminDialogVisible.value = false
        await loadAdminList()
      } else {
        ElMessage.error('创建管理员失败')
      }
    }
  } catch (e) {
  } finally {
    loading.value = false
  }
}

const handleConfirmRole = () => {
  // 实现角色分配逻辑
  ElMessage.success('角色分配成功')
  roleDialogVisible.value = false
}

// 角色选择变化时自动设置权限
const handleRoleChange = (roleName) => {
  const selectedRole = roleList.value.find(role => role.roleName === roleName)
  if (selectedRole) {
    adminForm.value.permissions = selectedRole.permissions || []
  }
}

// 加载管理员数据
const loadAdminList = async () => {
  loading.value = true
  try {
    const res = await getAdminUserList()
    // 期望后端响应结构：{ code, message, data, total }
    if (res && res.code === 200 && Array.isArray(res.data)) {
      adminData.value = res.data.map(item => ({
        id: item.admin_id,
        username: item.username,
        fullName: item.full_name || '',
        role: item.role_name || '审核员',
        permissions: item.permissions || [],
        status: 'active',
        createTime: item.creation_time || '',
        lastLoginTime: item.last_login_time || ''
      }))
    } else {
      ElMessage.error(res?.message || '获取管理员列表失败')
    }
  } catch (e) {
    // 已由拦截器统一处理
  } finally {
    loading.value = false
  }
}

// 加载权限信息
const loadPermissionsInfo = async () => {
  try {
    const res = await getAdminPermissionsInfo()
    if (res && res.code === 200 && res.data) {
      permissionMap.value = res.data.permissions || {}
      permissionsDescription.value = res.data.description || ''
    }
  } catch (e) {}
}

// 加载角色列表
const loadRoleList = async () => {
  try {
    const res = await getAdminRoleList()
    if (res && res.code === 200 && Array.isArray(res.data)) {
      roleList.value = res.data
    }
  } catch (e) {}
}

const handleSearch = async () => {
  loading.value = true
  try {
    const res = await searchAdminUsers({ searchTerm: searchTerm.value })
    if (res && res.code === 200 && Array.isArray(res.data)) {
      adminData.value = res.data.map(item => ({
        id: item.admin_id,
        username: item.username,
        fullName: item.full_name || '',
        role: item.role_name || '审核员',
        permissions: item.permissions || [],
        status: 'active',
        createTime: item.creation_time || '',
        lastLoginTime: item.last_login_time || ''
      }))
    } else {
      ElMessage.error(res?.message || '搜索管理员失败')
    }
  } catch (e) {
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  loadAdminList()
  loadPermissionsInfo()
  loadRoleList()
})
</script>

<style scoped>
.admin-management {
  padding: 0;
  width: 100%;
  min-height: 100%;
  box-sizing: border-box;
}

.admin-management h2 {
  margin-bottom: 20px;
  color: #333;
}

.tab-content {
  padding: 20px 0;
}

.action-bar {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
  width: 100%;
}

.filter-card {
  margin-bottom: 20px;
  width: 100%;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.detail-section {
  margin-top: 20px;
}

.detail-section h4 {
  margin-bottom: 10px;
  color: #333;
}

.detail-section p {
  color: #666;
  line-height: 1.6;
}

.detail-section pre {
  background-color: #f5f7fa;
  padding: 10px;
  border-radius: 4px;
  color: #666;
  font-size: 12px;
  overflow-x: auto;
}
</style> 